<?php
class Maven_ManageCatalogSpr_Model_Import extends Mage_Core_Model_Abstract
{
	public function initPhpSetting()
	{
		set_time_limit(0);
		ini_set('memory_limit','6048M');
	}
	public function isRunning($title)
	{
		$cols = Mage::getResourceModel('managecatalogspr/managecatalog')->getLast($title);
		if(isset($cols['status']) && $cols['status']==0){
			return true;
		}else {
			return false;
		}
	}
    
   	public function savePriceEntry($insObj,$id='',$complete=0)
	{
		$implog = Mage::getResourceModel('managecatalogspr/importlog');
		$mc = Mage::getModel('managecatalogspr/managecatalog');

		if($id) { //Update Entry
			$mc->load($id);
			$mc->setData('success',$implog->getSuccessCount());
			$mc->setData('fail',$implog->getFailCount());
			$mc->setData('update_time',Mage::getSingleton('core/date')->gmtDate());
			$mc->setData('status','0');
		}else {  //Insert New Entry
			$mc->setData('title','Price');
			$mc->setData('filename',addslashes($insObj->getFiles()));
			$mc->setData('created_time',Mage::getSingleton('core/date')->gmtDate());
			$mc->setData('status','0');
			$mc->setData('total',$implog->getCountData());
		}

		//if($implog->getPendingCount()==0)	{ //completed
		if($complete!=0)	{ //completed
			$mc->setData('status',$complete);
		}
		$mc->save();
		return $mc->getId();
	}
	public function runPrice()
	{
		$this->initPhpSetting();
		$con = Mage::getSingleton('core/resource')->getConnection('core_write');
		if($this->isRunning('Price')) {
			print $msg = "Price update process is running!";
			return $msg;
		}
		try {
			// INSERT PRODUCTS
        	$insObj = Mage::getModel('managecatalogspr/InsertProduct'); //new InsertProduct();
        	$insObj->cleanLog();
        	$insObj->downloadFiles();
			$insObj->process();
			$mc_id = $this->savePriceEntry($insObj);

			// Update Products
			$counter = 0;
			$countRes = $con->query("SELECT count(*) as total FROM import_log_spr WHERE estatus = 0 ORDER BY id ASC ")->fetchAll();
			if($countRes[0]['total'] == 0 ) {
				Mage::log("Product Database operation Already Done!", 7, Mage::getStoreConfig('managecatalogspr/price_file/log_file'));
				$insObj->sendStatus();
				unset($insObj);
				return "Product Database operation Already Done!";
			}else {
				$sth = $con->prepare("SELECT id,sku FROM import_log_spr WHERE estatus = 0 ORDER BY ID ASC LIMIT 0, 100");
				while($counter < $countRes[0]['total']) {
					$sth->execute();
					$res = $sth->fetchAll();
					//$res = $con->query("SELECT * FROM import_log WHERE estatus = 0 ORDER BY id ASC LIMIT 0, $limit ")->fetchAll();
					if(count($res)>0) {
						foreach ($res as $data) {
							$obj = Mage::getModel('managecatalogspr/ProductSave');
							$obj->loadProduct(array('id'=> $data['id'],'sku'=> $data['sku']));
							$obj->saveProduct();
							
							if($counter%100==0) {
								$this->savePriceEntry($insObj,$mc_id);
							}
							$counter++;
						}
					}else {
						break;
					}
				}
				$insObj->refreshAllCache(); // Cache Rebuild Process.
				Mage::log("Product Database operation Completed!", 7, Mage::getStoreConfig('managecatalog/price_file/log_file'));
				$insObj->sendStatus($mc_id);
				$this->savePriceEntry($insObj,$mc_id,1);
				unset($insObj);
				unset($obj);
				return "Product Database operation Completed!";
			}
		}catch (Exception $e) {
			if(isset($mc_id)) {
				$this->savePriceEntry($insObj,$mc_id);
			}
			return "Exception Thrown - ".$e->getMessage();
		}

	}
	
    public function saveQuickPriceEntry($ar, $id='')
	{
		$implog = Mage::getResourceModel('managecatalogspr/importlog');
		$mc = Mage::getModel('managecatalogspr/managecatalog');

		if($id!='') { //Update Entry
			$mc->load($id);			$mc->setData('update_time',Mage::getSingleton('core/date')->gmtDate());
			$mc->setData('status','0');
		}else {  //Insert New Entry
			$mc->setData('title','QuickPrice');
			$mc->setData('filename',addslashes($ar['files']));
			$mc->setData('created_time',Mage::getSingleton('core/date')->gmtDate());
			$mc->setData('status','0');
		}
		if(isset($ar['success'])) 	$mc->setData('success', $ar['success']);		
		if(isset($ar['fail'])) 		$mc->setData('fail',$ar['fail']);		
		if(isset($ar['total'])) 	$mc->setData('total',$ar['total']);


		if(isset($ar['status']) && $ar['status']==1)	{ //completed
			$mc->setData('status','1');
            $mc->setData('update_time',Mage::getSingleton('core/date')->gmtDate());
		}
		$mc->save();

		return $mc->getId();
	}
	
    public function runQuickPrice()
	{
		$this->initPhpSetting();
		if($this->isRunning('QuickPrice')) {
			print $msg = "QuickPrice update process is running! \n";
			//return $msg;
		}
		try {
			 print $msg = "Price import process is running! \n";  
			// INSERT PRODUCTS PRICE
			$priceObj = Mage::getModel('managecatalogspr/InsertProduct'); //new InsertProduct();
			$priceObj->cleanPriceLog();
			$priceObj->downloadFiles();
			$priceObj->processPrice();
			$msg = "QuickPrice Update processed completed! \n";
			Mage::log($msg, 7, Mage::getStoreConfig('managecatalog/priceupdate/pricelog_file'));
		}catch(Exception $e) {
			print $msg = "QuickPrice Update - Failure to process! - ". $e->getMessage();
			Mage::log($msg, 7, Mage::getStoreConfig('managecatalog/priceupdate/pricelog_file'));
		}
		return $msg;
	}
    
	public function saveSprStockEntry($ar, $id='')
	{
		$implog = Mage::getResourceModel('managecatalogspr/importlog');
		$mc = Mage::getModel('managecatalogspr/managecatalog');

		if($id!='') { //Update Entry
			$mc->load($id);			$mc->setData('update_time',Mage::getSingleton('core/date')->gmtDate());
			$mc->setData('status','0');
		}else {  //Insert New Entry
			$mc->setData('title','SprStock');
			$mc->setData('filename',addslashes($ar['files']));
			$mc->setData('created_time',Mage::getSingleton('core/date')->gmtDate());
			$mc->setData('status','0');
		}
		if(isset($ar['success'])) 	$mc->setData('success', $ar['success']);
		if(isset($ar['fail'])) 		$mc->setData('fail',$ar['fail']);
		if(isset($ar['total'])) 	$mc->setData('total',$ar['total']);


		if(isset($ar['status']) && $ar['status']==1)	{ //completed
			$mc->setData('status','1');
		}
		$mc->save();

		return $mc->getId();
	}
    
    public function runSprStock()
	{
	   $this->initPhpSetting();
		if($this->isRunning('SprStock')) {
			print $msg = "sprStock update process is running!";
			//return $msg;
		}
        try {
			$obj = Mage::getModel('managecatalogspr/SprStockUpdate');
			$obj->cleanLog();
			
			$obj->downloadFiles();
			$mc_id = $this->saveSprStockEntry(array('files' => $obj->getFiles()));
			$obj->setManageCatalogId($mc_id);
			$obj->process();
			$this->saveSprStockEntry(array('files' => $obj->getFiles(), 'status'=>1), $mc_id);
			$obj->sendStatus($mc_id);
			$msg = "SPRicahrd Stock Update processed completed!";
			$this->reIndex();
		    Mage::log($msg, 7, Mage::getStoreConfig('managecatalogspr/spr_stock_update/log_file'));
  		}catch(Exception $e) {
			print $msg = "SPRicahrd Stock Update - Failure to process! - ". $e->getMessage();
			Mage::log($msg, 7, Mage::getStoreConfig('managecatalog/spr_stock_update/log_file'));
		}
		return $msg;
	}
   	public function reIndex()
    {
        $indexterPath=Mage::getBaseDir()."/shell/indexer.php";
		Mage::app()->cleanCache();
		if(file_exists($indexterPath)){  
				system("php ".$indexterPath." --reindex catalog_product_attribute,catalog_product_price,catalog_url,catalog_product_flat,catalog_category_flat,catalog_category_product,cataloginventory_stock");
        }
		Mage::app()->cleanCache();
    }
	
}